package com.chat.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chat.domain.converter.UserConverter;
import com.chat.domain.dto.user.UserPasswordDTO;
import com.chat.domain.dto.user.UserProfileDTO;
import com.chat.domain.pojo.User;
import com.chat.excpetion.CustomException;
import com.chat.mapper.UserMapper;
import com.chat.service.UserService;
import com.chat.util.ResultCodeEnum;
import com.chat.util.SecurityHolderUtil;
import jakarta.servlet.http.HttpSession;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author wb
 * @since 2024-08-19
 */

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Cacheable(value = "friends", keyGenerator = "keyGenerator")
    @Override
    public List<User> getFriendsByUserId(Integer userId) {
        return baseMapper.selectUserFriends(userId);
    }


    @Override
    public List<User> getUsersByGroupId(Integer groupId) {
        return baseMapper.selectUsersByGroupId(groupId);
    }

    @Override
    public User getUserByUsername(String username) {
        return baseMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
    }


    @Override
    public Boolean updateProfile(UserProfileDTO userProfileDTO, HttpSession session) {
        User user = UserConverter.INSTANCE.toEntity(userProfileDTO);
        Boolean result = super.updateById(user);

        session.setAttribute("user", baseMapper.selectById(user.getId()));

        return result;
    }

    @Override
    public Boolean updatePassword(UserPasswordDTO userPasswordDTO, HttpSession session) {
        User user = SecurityHolderUtil.getUser(session);
        String salt = user.getSalt();

        // 判断旧密码是否正确
        if (!user.getPassword().equals(DigestUtil.md5Hex(userPasswordDTO.getOldPwd() + salt))) {
            throw new CustomException(ResultCodeEnum.OLD_PASSWORD_ERROR);
        }

        // 设置新密码
        user.setPassword(DigestUtil.md5Hex(userPasswordDTO.getNewPwd() + salt));

        return super.updateById(user);
    }
}
